import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:magma/heartbeat/helpers/magma_tap.dart';
import 'package:qlevar_router/qlevar_router.dart';
import 'package:stacked/stacked.dart';
import '../../heartbeat/helpers/magma_text_style.dart';
import '../../heartbeat/helpers/magma_color.dart';
import '../../heartbeat/helpers/magma_toast.dart';
import '../../heartbeat/parts/login_required_dialog.dart';
import '../../comms_link/app_state.dart';
import '../../heartbeat/blueprint/user_model.dart';
import '../../heartbeat/blueprint/club_model.dart';

/// 成员列表页面视图模型
class MemberListNavigatorViewModel extends BaseViewModel {
  String _clubId = '';
  String get clubId => _clubId;

  /// 获取当前用户
  UserModel? get currentUser => appState.userStore.currentUser;

  /// 检查是否已登录
  bool get isLoggedIn => appState.userStore.isLoggedIn;

  /// 初始化数据
  void setupData(String clubId) {
    _clubId = clubId;
    notifyListeners();
  }

  /// 获取俱乐部信息
  ClubModel? get club {
    return appState.clubManager.locateClub(_clubId);
  }

  /// 获取俱乐部成员列表
  List<UserModel> get members {
    final club = this.club;
    if (club == null) return [];

    return club.memberIds
        .map((id) => appState.userStore.getUserById(id))
        .whereType<UserModel>()
        .toList();
  }

  /// 检查当前用户是否关注了某个用户
  bool checkFollowingStatus(String targetUserId) {
    if (!isLoggedIn) return false;
    return appState.followManager.isFollowing(currentUser!.id, targetUserId);
  }

  /// 切换关注状态
  Future<bool> toggleFollowStatus(String targetUserId) async {
    if (!isLoggedIn) return false;

    final isFollowing = checkFollowingStatus(targetUserId);

    if (isFollowing) {
      final result = await appState.followManager.terminateFollow(
        followerId: currentUser!.id,
        followingId: targetUserId,
      );
      if (result) notifyListeners();
      return result;
    } else {
      final result = await appState.followManager.establishFollow(
        followerId: currentUser!.id,
        followingId: targetUserId,
      );
      if (result) notifyListeners();
      return result;
    }
  }
}

/// 成员列表页面
class MemberListStory extends StatelessWidget {
  final String clubId;

  const MemberListStory({super.key, required this.clubId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<MemberListNavigatorViewModel>.reactive(
      viewModelBuilder: () => MemberListNavigatorViewModel(),
      onViewModelReady: (viewModel) {
        viewModel.setupData(clubId);
      },
      builder: (context, viewModel, child) {
        final club = viewModel.club;

        if (club == null) {
          return Scaffold(
            backgroundColor: MagmaColor.black,
            body: Center(
              child: Text(
                'Club not found',
              ).inter(fontSize: 16.sp, color: MagmaColor.white),
            ),
          );
        }

        return Scaffold(
          backgroundColor: MagmaColor.black,
          appBar: AppBar(
            backgroundColor: MagmaColor.black,
            leading: MagmaTap(
              onTap: () => QR.back(),
              child: Icon(
                Icons.arrow_back,
                color: MagmaColor.white,
                size: 24.w,
              ),
            ),
            title: Text('Member').blackHanSans(
              fontSize: 24.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w700,
            ),
            centerTitle: true,
          ),
          body:
              viewModel.members.isEmpty
                  ? Center(
                    child: Text('No members found').inter(
                      fontSize: 14.sp,
                      color: MagmaColor.white.withOpacity(0.5),
                    ),
                  )
                  : ListView.builder(
                    padding: EdgeInsets.symmetric(
                      horizontal: 20.w,
                      vertical: 16.h,
                    ),
                    itemCount: viewModel.members.length,
                    itemBuilder: (context, index) {
                      final member = viewModel.members[index];
                      return _buildMemberItem(context, member, viewModel);
                    },
                  ),
        );
      },
    );
  }

  /// 构建成员项
  Widget _buildMemberItem(
    BuildContext context,
    UserModel member,
    MemberListNavigatorViewModel viewModel,
  ) {
    return Container(
      margin: EdgeInsets.only(bottom: 12.h),
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      decoration: BoxDecoration(
        color: MagmaColor.white.withOpacity(0.15),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(color: MagmaColor.white, width: 1.w),
      ),
      child: Row(
        children: [
          // 用户头像
          CircleAvatar(
            radius: 28.r,
            backgroundImage: AssetImage(member.avatar),
          ),

          SizedBox(width: 12.w),

          // 用户名
          Expanded(
            child: Text(member.username).blackHanSans(
              fontSize: 16.sp,
              color: MagmaColor.white,
              fontWeight: FontWeight.w600,
            ),
          ),

          // 关注按钮
          StatefulBuilder(
            builder: (context, setState) {
              final isFollowing = viewModel.checkFollowingStatus(member.id);
              final isSelf =
                  viewModel.isLoggedIn &&
                  viewModel.currentUser?.id == member.id;

              if (isSelf) return const SizedBox.shrink();

              return MagmaTap(
                onTap: () async {
                  if (!viewModel.isLoggedIn) {
                    await LoginRequiredDialog.show(context);
                    return;
                  }

                  // 检查是否是关注自己
                  if (viewModel.currentUser?.id == member.id) {
                    MagmaToast.error(
                      context,
                      title: 'You cannot follow yourself',
                    );
                    return;
                  }

                  final wasFollowing = isFollowing;
                  final result = await viewModel.toggleFollowStatus(member.id);

                  if (result) {
                    setState(() {});
                    if (context.mounted) {
                      MagmaToast.success(
                        context,
                        title: wasFollowing ? 'Unfollowed' : 'Followed',
                      );
                    }
                  }
                },
                child: Container(
                  padding: EdgeInsets.symmetric(
                    horizontal: 12.w,
                    vertical: 8.h,
                  ),
                  decoration: BoxDecoration(
                    color: isFollowing ? Colors.transparent : MagmaColor.purple,
                    borderRadius: BorderRadius.circular(20.r),
                    border:
                        isFollowing
                            ? Border.all(color: MagmaColor.white, width: 1.w)
                            : null,
                  ),
                  child: Text(
                    isFollowing ? 'Following' : '+follow',
                  ).blackHanSans(
                    fontSize: 14.sp,
                    color: isFollowing ? MagmaColor.white : MagmaColor.black,
                    fontWeight: FontWeight.w600,
                  ),
                ),
              );
            },
          ),
        ],
      ),
    );
  }
}
